#ifndef __SOCK_HPP__
#define __SOCK_HPP__

#include <iostream>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

class Sock
{
private:
    static const int g_backlog = 10;

public:
    bool Socket()
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
            return false;
        return true;
    }

    bool Bind(uint16_t port, const std::string &ip = "0.0.0.0")
    {
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = inet_addr(ip.c_str());
        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            return false;
        return true;
    }

    bool Listen(int backlog = g_backlog)
    {
        if (listen(_sockfd, backlog) < 0)
            return false;
        return true;
    }

    int Accept(uint16_t *port, std::string *ip)
    {
        struct sockaddr_in peer;
        bzero(&peer, sizeof(peer));
        socklen_t len = sizeof(peer);
        int sockfd = accept(_sockfd, (struct sockaddr *)&peer, &len);
        if (sockfd < 0)
            return -1;
        *port = ntohs(peer.sin_port);
        *ip = inet_ntoa(peer.sin_addr);
        return sockfd;
    }

    bool Connect(uint16_t port, const std::string &ip)
    {
        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        if (connect(_sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
            return false;
        return true;
    }

    bool ReuseAddr()
    {
        int opt = 1;
        if (setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)) < 0)
            return false;
        return true;
    }

    bool CreateServer(uint16_t port,const std::string& ip="0.0.0.0")
    {
        if(!Socket()) return false;
        if(!Bind(port,ip)) return false;
        if(!Listen()) return false;
        if(!ReuseAddr()) return false;
        return true;
    }

    bool CreateClient(uint16_t port,const std::string& ip)
    {
        if(!Socket()) return false;
        if(!Connect(port,ip)) return false;
        return true;
    }

    int Fd()
    {
        return _sockfd;
    }

private:
    int _sockfd = -1;
};

#endif